<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ProblemApi } from '@/api/ProblemApi.ts'
import type { AdminProblemVO, SearchByAdminParams } from '@/api/Problem.ts'
import { message } from 'ant-design-vue'
import { ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue'
import DeleteDialog from './components/DeleteDialog.vue'
import InfoDialog from './components/InfoDialog.vue'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 80,
  },
  {
    title: '题目标题',
    dataIndex: 'title',
    key: 'title',
    align: 'center',
    width: 200,
  },
  {
    title: '难度',
    dataIndex: 'difficulty',
    key: 'difficulty',
    align: 'center',
    width: 80,
  },
  {
    title: '创建者ID',
    dataIndex: 'createdUserId',
    key: 'createdUserId',
    align: 'center',
    width: 120,
  },
  {
    title: '可见性',
    dataIndex: 'visible',
    key: 'visible',
    align: 'center',
    width: 80,
  },
  {
    title: '提交次数',
    dataIndex: 'submissionCount',
    key: 'submissionCount',
    align: 'center',
    width: 100,
  },
  {
    title: '通过次数',
    dataIndex: 'acceptedCount',
    key: 'acceptedCount',
    align: 'center',
    width: 100,
  },
  {
    title: '通过率',
    key: 'passRate',
    align: 'center',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 160,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 120,
  },
];

const loading = ref(false)
const tableData = ref<AdminProblemVO[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const queryParams = ref<SearchByAdminParams>({
  title: null,
  difficulty: null,
  createdUserId: null,
  visible: null,
})

const sanitizeParams = (params: SearchByAdminParams) => {
  return {
    title: params.title !== null && String(params.title).trim() !== '' ? String(params.title).trim() : null,
    difficulty: params.difficulty !== null && params.difficulty >= 0 ? params.difficulty : null,
    createdUserId: params.createdUserId !== null && String(params.createdUserId).trim() !== '' ? String(params.createdUserId).trim() : null,
    visible: params.visible !== null && params.visible >= 0 ? params.visible : null,
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...sanitizeParams(queryParams.value),
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await ProblemApi.searchByAdmin(params)
    tableData.value = data?.records || []
    pagination.current = data?.pageNumber || 1
    pagination.pageSize = data?.pageSize || 10
    pagination.total = data?.totalRow || 0
  } catch (error) {
    message.error('获取题目列表失败')
    console.error('获取题目列表失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})

const onSearch = () => {
  pagination.current = 1
  fetchData()
}

const onReset = () => {
  queryParams.value = {
    title: null,
    difficulty: null,
    createdUserId: null,
    visible: null
  }
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 10
  fetchData()
}

const getDifficultyColor = (difficulty: number) => {
  switch (difficulty) {
    case 0:
      return 'green'
    case 1:
      return 'blue'
    case 2:
      return 'orange'
    case 3:
      return 'red'
    default:
      return 'default'
  }
}

const getDifficultyLabel = (difficulty: number) => {
  switch (difficulty) {
    case 0:
      return '简单'
    case 1:
      return '中等'
    case 2:
      return '困难'
    case 3:
      return '极难'
    default:
      return '未知'
  }
}

const getVisibleLabel = (visible: number) => {
  switch (visible) {
    case 0:
      return '隐藏'
    case 1:
      return '可见'
    default:
      return '未知'
  }
}

const getVisibleColor = (visible: number) => {
  switch (visible) {
    case 0:
      return 'red'
    case 1:
      return 'green'
    default:
      return 'default'
  }
}

const formatPassRate = (record: AdminProblemVO) => {
  const submit = Number(record?.submissionCount ?? 0)
  const solved = Number(record?.acceptedCount ?? 0)
  if (!submit || submit <= 0) return '0.00%'
  const rate = (solved / submit) * 100
  return `${rate.toFixed(2)}%`
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 详情弹窗
const infoDialogVisible = ref(false)
const viewingProblem = ref<AdminProblemVO | null>(null)

const onView = (record: AdminProblemVO) => {
  viewingProblem.value = record
  infoDialogVisible.value = true
}

const onEdit = (record: AdminProblemVO) => {
  router.push(`/admin/problem/edit/${record.id}`)
}

// 删除弹窗
const deleteDialogVisible = ref(false)
const deletingProblem = ref<AdminProblemVO | null>(null)

const onDelete = (record: AdminProblemVO) => {
  deletingProblem.value = record
  deleteDialogVisible.value = true
}

const onDeleteSuccess = () => {
  fetchData()
}

const onAction = (key: string, record: AdminProblemVO) => {
  switch (key) {
    case 'edit':
      onEdit(record)
      break
    case 'view':
      onView(record)
      break
    case 'delete':
      onDelete(record)
      break
    default:
      break
  }
}

const onMenuClick = (info: any, record: AdminProblemVO) => {
  onAction(String(info?.key ?? ''), record)
}

// 路由跳转
const router = useRouter()

const onAddProblem = () => {
  router.push('/admin/problem/add')
}
</script>

<template>
  <div class="w-full">
    <a-card
      class="w-full rounded-lg shadow-sm"
      :bodyStyle="{ padding: '24px' }"
    >
      <template #title>
        <div class="flex items-center justify-between">
          <span class="text-lg font-semibold text-gray-800">题目管理</span>
          <a-button type="primary" @click="onAddProblem" class="flex items-center gap-2">
            <PlusOutlined />
            新增题目
          </a-button>
        </div>
      </template>
      <!-- 搜索表单 -->
      <div class="mb-6 flex flex-wrap items-center gap-4">
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">标题:</label>
          <a-input
            v-model:value="queryParams.title"
            placeholder="输入题目标题"
            allow-clear
            @pressEnter="onSearch"
            class="w-[200px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">难度:</label>
          <a-select
            v-model:value="queryParams.difficulty"
            placeholder="选择难度"
            allow-clear
            class="w-[120px]"
          >
            <a-select-option :value="0">简单</a-select-option>
            <a-select-option :value="1">中等</a-select-option>
            <a-select-option :value="2">困难</a-select-option>
            <a-select-option :value="3">极难</a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">创建者ID:</label>
          <a-input
            v-model:value="queryParams.createdUserId"
            placeholder="输入创建者ID"
            allow-clear
            @pressEnter="onSearch"
            class="w-[150px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">可见性:</label>
          <a-select
            v-model:value="queryParams.visible"
            placeholder="选择可见性"
            allow-clear
            class="w-[120px]"
          >
            <a-select-option :value="0">隐藏</a-select-option>
            <a-select-option :value="1">可见</a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2">
          <a-button type="primary" @click="onSearch" class="px-6">
            搜索
          </a-button>
          <a-tooltip title="重置">
            <a-button
              @click="onReset"
              :shape="'default'"
              class="w-9 h-9 p-0 flex items-center justify-center"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-tooltip>
        </div>
      </div>

      <!-- 题目表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showTotal: (total: number) => `共 ${total} 条`
        }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
        class="rounded-lg"
        :customRow="(record: any) => ({ class: 'hover:bg-slate-50' })"
        :customHeaderRow="() => ({ class: 'bg-slate-50 border-b-2 border-slate-200' })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'difficulty'">
            <a-tag :color="getDifficultyColor(record.difficulty)" class="px-2 py-1 rounded-full text-xs font-medium">
              {{ getDifficultyLabel(record.difficulty) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'visible'">
            <a-tag :color="getVisibleColor(record.visible)" class="px-2 py-1 rounded-full text-xs font-medium">
              {{ getVisibleLabel(record.visible) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'passRate'">
            <span class="text-sm font-medium text-gray-700">{{ formatPassRate(record) }}</span>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <span class="text-sm text-gray-600">{{ formatDateTime(record.createTime) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-dropdown :trigger="['click']">
              <a-button type="link" size="small" class="text-blue-600 hover:text-blue-800 font-medium">
                操作
              </a-button>
              <template #overlay>
                <a-menu @click="onMenuClick($event, record)" class="rounded-lg shadow-lg border border-gray-200">
                  <a-menu-item key="view" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">查看详情</span>
                  </a-menu-item>
                  <a-menu-item key="edit" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">编辑</span>
                  </a-menu-item>
                  <a-menu-divider class="my-1" />
                  <a-menu-item key="delete" class="hover:bg-red-50 transition-colors">
                    <span class="text-red-600">删除</span>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情弹窗 -->
    <InfoDialog
      v-model:visible="infoDialogVisible"
      :problem="viewingProblem"
    />

    <!-- 删除弹窗 -->
    <DeleteDialog
      v-model:visible="deleteDialogVisible"
      :problem="deletingProblem"
      @success="onDeleteSuccess"
    />
  </div>
</template>

